<?php
namespace app\index\controller;
use think\Controller;
use think\Db;
use think\Session;
use think\Request;

class Index extends Controller{
    const APPID = 'wx84aaab0c4330e9f7';
    const APPSECRET = '8079695bba931fe5ace1df0a80f3f69b';
    public function index(){
        return $this->view->fetch();
    }
    public function auth(){
        //测试
        exit('404');
        if( !session('wapUserInfo') ){
            vendor('weixin.Weixin');
            $wTool = new \Weixin();
            $openid = Session::get("AUTHORIZATION-Wechat-Openid");
            if( !$openid ) {
                $weiRes = $wTool->getInfoSilence('http://'.$_SERVER['SERVER_NAME'].'/Index/index',self::APPID,self::APPSECRET);
                if( $weiRes ) {
                    Session::set("AUTHORIZATION-Wechat-Openid",$weiRes->openid);
                } else {
                    exit('error');
                }
                $_GET['code'] = null;
            }
            (is_null($openid) || empty($openid) || '' == $openid) && exit('php.ini error->file_get_contents!');
            $request = Request::instance();
            $userInfo = Db::table('__USER__')->where("openid='$openid'")->find();
            if( $userInfo ) {
                $data = [
                    'last_ip'=>$request->ip(),
                    'last_time'=>time(),
                    'update_time'=> time()
                ];
                Db::table('__USER__')->where(['id'=>$userInfo['id']])->update($data);
                $data = array_merge($userInfo,$data);
            } else {
                $res = $wTool->getInfo('http://'.$_SERVER['SERVER_NAME'].'/Index/index',self::APPID,self::APPSECRET); //显示授权
                $data = [
                    'openid' => $res->openid,
                    'nickname' => isset($res->nickname) ? $res->nickname : '',
                    'headimg' => isset($res->headimgurl) ? $res->headimgurl : '/Public/wap/img/mrtx.png',
                    'create_time' => time(),
                    'update_time'=> time(),
                    'status' => 1,
                    'last_ip'=>$request->ip(),
                    'last_time'=>time(),
                ];
                $data['id'] = Db::table('__USER__')->insert($data);
            }
            session('wapUserInfo',$data);
            var_dump(session('wapUserInfo'));
        }
        exit;
    }


}
